var baseUrl = require('../../utils/urllink.js')
var app = getApp();
var sliderWidth = 187.5; // 需要设置slider的宽度，用于计算中间位置
// var WxParse = require('../../wxParse/wxParse.js');
Page({
  data: {
    images: [],
    info: [],
    spec: [],
    attr:[],
    goods_name: '',
    goods_id: '',
    goods_remark:'',
    cost_price: '',
    market_price: '' ,
    shop_price: '' ,
    store_count: '' ,
    store_id: '',
    cash_back:'',//利润
    goods_categoryid: '' ,//分类3
    brand_id: '',//品牌id
    currentItem: '' ,
    //还需要 分类的名称   属性的值
    province: '' ,//分类名 1级
    city: '',//分类名 2级
    district: '' ,//分类名 3级
    is_show_shuxing: true,
    shuxing_list: [],
    shoucang_show:false,
    agent_type:0,
    leader_id:0,
    shop_id:0,//B的店铺ID
    is_show:false,
    is_own:0,
    othergoodslist:[],
    storelist:[],
    is_othergoodslist:false,
    is_storelist:false,
    hostimgs: app.globalData.hostimgs,
  },

  //返回顶部
  scrolltop: function () {
    this.setData({
      scrolltop: 0
    })
  },
  tabClick: function (e) {
    var that = this
    that.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });

  },
  onLoad: function (options) {
   var that = this;
   console.log('toshangping传过来的goods_id参数' + options.goods_id)

   var goods_id = options.goods_id;
   var leader_id = options.leader_id;
   //登录调用
   getApp().getUserInfo(function (userInfo, openid1) {

    that.setData({
      goods_id:goods_id,
      leader_id: leader_id,
      agent_type: app.globalData.agent_type,
      shop_id: app.globalData.shop_id,
      hostimgs: app.globalData.hostimgs,
    })
    app.globalData.leader_id = leader_id;// 推广者上级
    //获取商品详情
    get_goods(that, goods_id)
   })
  
  },
  onShow: function () {
    var that = this;
    that.setData({
      agent_type: app.globalData.agent_type,
      shop_id: app.globalData.shop_id,
    })
  },
  onScroll: function (e) {
    if (e.detail.scrollTop > 100 && !this.data.scrollDown) {
      this.setData({
        scrollDown: true
      });
    } else if (e.detail.scrollTop < 100 && this.data.scrollDown) {
      this.setData({
        scrollDown: false
      });
    }
  },

  makePhoneCall: function () {
    wx.makePhoneCall({
      phoneNumber: '13553835046' //仅为示例，并非真实的电话号码
    })
  },

  //分享
  onShareAppMessage: function (event) {
    var agent_type = app.globalData.agent_type;
    var goods_id = this.data.goods_id;
    if(agent_type == 1){
      return {
        title: this.data.goods_name,
        desc: this.data.goods_name,
        path: '/pages/goods/detail?goods_id=' + goods_id + '&leader_id=' + getApp().globalData.userid
      }
    }

  },



  //一键保存图片和复制文字
  yijiansave: function (event) {
    var that = this;
    var goods_id = event.currentTarget.dataset.id
    console.log('一键保存');
    var shop_id = app.globalData.shop_id
    var is_own = that.data.is_own;
    if(shop_id <= 0){
       //弹出提示，去创建商铺，添加商品（选货）
      wx.showModal({
        title: '提示',
        content: '还没有创建您的店铺，快去吧',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.navigateTo({
              url: '../dianpu/savedianpu',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else{
      
      if (is_own == 0) {
        //店铺没有加该商品
        wx.showModal({
          title: '提示',
          content: '抱歉，您店铺中没有该商品，先去选货吧',
          showCancel:false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }else{
        //用户存在店铺，可以分享生成图片
        // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope
        wx.getSetting({
          success(res) {
            if (!res['scope.writePhotosAlbum']) {
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
                  wx.saveImageToPhotosAlbum()
                }
              })
            }
          }
        })
        //调用生成短链接，设置系统剪贴板的内容
        getduanurl(that, app.globalData.user_id, goods_id)

        //生成二维码
        getewmpic(that, app.globalData.user_id, that.data.goods_id) 
        
      }

    }
    



  },

  //跳转到商品详情页面
  todetail: function (e) {
    var goods_id = e.currentTarget.dataset.id;
    wx.redirectTo({
      url: '../goods/detail?goods_id=' + goods_id,
    })

  },

  //跳转到门店
  tomendian: function (event) {
    var id = event.currentTarget.dataset.id
    wx.navigateTo({
      url: 'detail?id=' + id
    })
  },
  //我的店铺首页
  toshop: function (e) {
    var that = this
    var shop_id = e.currentTarget.dataset.id
    // wx.navigateTo({
    //   url: '../dianpu/dianpu_goods_list',
    // })

    //跳转到另一个小程序
    wx.navigateToMiniProgram({
      appId: 'wxbceb417181a3492f',
      path: 'pages/shop/detail/index?id=' + shop_id,
      extraData: {
        foo: 'bar'
      },
      success(res) {
        // 打开成功
      }
    })
  },
  //B权限  把商品加入到b的小店中
  jiarudianpu: function (event){
    var that = this
    var goods_id = event.currentTarget.dataset.id;
    //var user_id = app.globalData.user_id;
    //var shop_id = event.currentTarget.dataset.shopid;

    xuanhuo(that, that.data.shop_id, goods_id) 
  },

  //预览图片
  previewImage: function (e) {
    var images = this.data.images;
    var that = this;
    var id = e.currentTarget.dataset.id;
    var files = []
    for(var i=0;i<images.length;i++){
      files[i] = that.data.hostimgs + images[i].image_url;
    }
    console.log(id)
    wx.previewImage({
      current: id, // 当前显示图片的http链接
      urls: files // 需要预览的图片http链接列表
    })
  },

  //收藏
  shoucang:function(e){
    var that = this
    var goods_id = e.currentTarget.dataset.id
    // 收藏 和 取消收藏
    collect_goods_op(that, app.globalData.user_id, goods_id)

  },

  //跳转到个人中心
  minetap:function(){
    wx:wx.switchTab({
      url: '../mine/mine',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  }

});


//查询一个商品
function get_goods(that, goods_id) {
  console.log(goods_id)
  //请求服务器
  wx.request({
    url: baseUrl+'weapp/Goods/get_goods_detail.html',

    data: {
      goods_id:goods_id,
      user_id:app.globalData.user_id,
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      'content-type': 'application/json'
    }, // 设置请求的 header
    success: function (res) {
      console.log("获取商品返回值")
      console.log(res.data)
      if(res.data.code == -1){
        // 商品编号错误 没有返回数据
        wx.showModal({
          title: '提示',
          content: '商品不存在!',
          showCancel:false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.switchTab({
                url: '../mine/mine',
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      } else if (res.data.code == -2){
        wx.showModal({
          title: '提示',
          content: '商品已经下架',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.switchTab({
                url: '../mine/mine',
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }else{
        that.setData({
          images: res.data.images,
          spec: res.data.spec,
          attr: res.data.attr,
          goods_name: res.data.info.goods_name,
          goods_id: res.data.info.goods_id,
          goods_remark:res.data.info.goods_remark,
          cost_price: res.data.info.cost_price,
          cash_back: res.data.info.cash_back,
          market_price: res.data.info.market_price,
          shop_price: res.data.info.shop_price,
          store_count: res.data.info.store_count,
          store_id: res.data.info.store_id,
          goods_categoryid: res.data.info.cat_id3,//分类3
          brand_id: res.data.info.brand_id,//品牌id
          currentItem: res.data.info.brand_id,
          is_show_shuxing: true,
          agent_type: app.globalData.agent_type,
          is_show:true,
          is_own:res.data.is_own,//是否被该用户选择
        })
        
        //判断是否收藏当前商品
        is_collect_goods(that, app.globalData.user_id, res.data.info.goods_id)
        //获取该店铺下其他商品limit2
        getothergoods(that, res.data.info.goods_id)
        //获取店铺信息
        getshop(that, res.data.info.goods_id)
      }


    },
    fail: function () {
    },
    complete: function () {
      // complete
    }
  })
}


//判断是否收藏当前商品
function is_collect_goods(that,user_id, goods_id) {
  //请求服务器
  wx.request({
    url: baseUrl +'weapp/Users/is_collect_goods.html',
    data: {
      user_id:user_id,
      goods_id: goods_id,

    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      'content-type': 'application/json'
    }, // 设置请求的 header
    success: function (res) {
      console.log(res.data)
      if(res.data.code == 1){
        // 收藏了 code==1
        that.setData({
          shoucang_show: true,
        })
      }
    },
    fail: function () {
    },
    complete: function () {
      // complete
    }
  })
}

//收藏当前商品
function collect_goods_op(that, user_id, goods_id) {
  //请求服务器
  wx.request({
    url: baseUrl +'weapp/Users/collect_goods_op.html',
    data: {
      user_id: user_id,
      goods_id: goods_id,
      shop_id:that.data.shop_id,
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      'content-type': 'application/json'
    }, // 设置请求的 header
    success: function (res) {
      console.log(res.data)
      if(res.data.type == 'del'){
        wx.showToast({
          title: '取消收藏',
        })
        that.setData({
          shoucang_show: false,
        })
      }else{
        wx.showToast({
          title: '收藏成功',
        })
        that.setData({
          shoucang_show: true,
        })
      }
    },
    fail: function () {
    },
    complete: function () {
      // complete
    }
  })
}


//一键保存图片  生成微信二维码+水印
function getewmpic(that, user_id, goods_id) {
  wx.showLoading({
    title: '加载图片...',
  })
  //请求服务器
  wx.request({
    url: baseUrl +'weapp/SavePicApi/save_ewmpic.html',
    data: {
      user_id: user_id,
      goods_id: goods_id,
      shop_id:app.globalData.shop_id,

    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      'content-type': 'application/json'
    }, // 设置请求的 header
    success: function (res) {
      console.log(res.data)
      that.setData({
        goods_id:goods_id,
      })
      if(res.data.code == 1){
        //生成的带二维码商品图片
        var picurl = res.data.img;
        wx.getImageInfo({
          src: picurl,
          success: function (res) {
            console.log(res.width)
            console.log(res.height)
            console.log(res.path)
            wx.saveImageToPhotosAlbum({
              filePath: res.path,
              success(res) {
                console.log(res);
  
                // wx.showToast({
                //   title: '保存图片成功',
                //   icon: 'success',
                //   duration: 3000
                // })
                wx.hideLoading()
                wx.showModal({
                  title: '成功保存图片',
                  content: '已成功为您保存图片到手机相册，复制文字链接到剪切板，请自行前往朋友圈分享',
                  showCancel: false,
                  confirmText:'知道了',
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    } else if (res.cancel) {
                      console.log('用户点击取消')
                    }
                  }
                })
              },
              fail: function () {
                console.log('fail');
                // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
                wx.getSetting({
                  success(res) {
                    console.log(res)
                    console.log(res.authSetting['scope.writePhotosAlbum'])
                    if (res.authSetting['scope.writePhotosAlbum'] == false) {

                      wx.openSetting({
                        success: (res) => {
                            res.authSetting = {
                              "scope.writePhotosAlbum": true
                            }
                            getewmpic(that, app.globalData.user_id, that.data.goods_id) 
                        }
                      })
                    }
                  }
                })
                wx.showToast({
                  title: '保存图片失败',
                  icon: 'success',
                  duration: 3000
                })

              },
              complete: function () {
              }
            })
          }
        })
      }else{
        wx.showToast({
          title: '图片错误',
          icon: 'success',
          duration: 3000
        })
      }





    },
    fail: function () {
      // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.writePhotosAlbum'] == false) {
            wx.openSetting({
              success: (res) => {
                res.authSetting = {
                  "scope.writePhotosAlbum": true
                }
                getewmpic(that, app.globalData.user_id, that.data.goods_id)
              }
            })
          }
        }
      })
    },
    complete: function () {
      // complete
    }
  })
}

//获取短链接
function getduanurl(that, user_id, goods_id) {
  var ShareLink = baseUrl +"index.php?m=Mobile&c=Goods&a=goodsInfo&id=" + goods_id +"&first_leader="+user_id;
  //请求服务器
  wx.request({
    url: baseUrl +'index.php?m=Mobile&c=Url&a=ajaxGetUrl',
    data: {
      link: ShareLink
    },
    method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      'content-type': 'application/json'
    }, // 设置请求的 header
    success: function (res) {
      console.log(res.data)
      var url = app.globalData.duan_url+res.data;
      //设置系统剪贴板的内容
      wx.setClipboardData({
        data: that.data.goods_name+url,
      })
      
    },
    fail: function () {
    },
    complete: function () {
      // complete
    }
  })
}


// 选货 选择当前商品
function xuanhuo(that, shop_id, goods_id) {
  if(shop_id == 0){
    wx.showModal({
      title: '提示',
      content: '请先完善店铺资料',
      showCancel: false,

      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.navigateTo({
            url: '../dianpu/savedianpu',
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  }else{

  
    //请求服务器
    wx.request({
      url: baseUrl + 'weapp/Goods/add_shop_goods.html',
      data: {
        shop_id: shop_id,
        goods_id: goods_id,

      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'content-type': 'application/json'
      }, // 设置请求的 header
      success: function (res) {
        console.log(res.data)
        if(res.data.code == -1){
          //你已经添加过该商品啦！
          wx.showToast({
            title: '已添加该商品',
          })
          that.setData({
            is_own: 1,
          })
        } else if (res.data.code == -2){
          //当前商品不存在或已下架！
          wx.showToast({
            title: '商品不存在或已下架',
          })
        }else{
          wx.showToast({
            title: '选货成功',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            is_own:1,
          })
        }
      },
      fail: function () {
      },
      complete: function () {
        // complete
      }
    })
  }
}

//获取该商品的店铺下其他商品 limit 2
function getothergoods(that,goods_id){
  //请求服务器
  wx.request({
    url: baseUrl + 'weapp/Goods/recommend_goods.html',
    data: {
      goods_id: goods_id,
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {'content-type': 'application/json'}, // 设置请求的 header
    success: function (res) {
      console.log(res.data)
      if(res.data.code == 0){
        that.setData({
          othergoodslist:res.data.list,
          is_othergoodslist:true,
        })
      }
    },
    fail: function () {},
    complete: function () {}
  })
}

//获取店铺信息
function getshop(that, goods_id){
  //请求服务器
  wx.request({
    url: baseUrl + 'weapp/Store/store_data_by_goods.html',
    data: {
      goods_id: goods_id,
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: { 'content-type': 'application/json' }, // 设置请求的 header
    success: function (res) {
      console.log(res.data)
      if (res.data.code == 0) {
        that.setData({
          storelist: res.data.data,
          is_storelist:true,
          shop_id: res.data.data.shop_id,
        })
      }
    },
    fail: function () { },
    complete: function () { }
  })
}

